<template>
  <bc-modal :size="[360, 120]" type="dialog" title="转移" v-model="dialogVisible" footer>
    <el-form ref="ruleFormRef" :model="formData" label-width="auto">
      <bc-form
        ref="tbcFormRef"
        :fields="fields"
        :mode="'add'"
        @change="handleChange"
        :border="false"
        padding="0"
        :cols="1"
      >
      </bc-form>
    </el-form>
    <template #footer>
      <el-button @click="colse">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </template>
  </bc-modal>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import BcForm from '@/components/bcForm/Index.vue'
import { ElMessage } from 'element-plus'

const fields = [
  {
    label: '原销售',
    prop: 'fromAdvisorId',
    type: 'select',
    linkage: 'communityId',
    options: async (params) => {
      try {
        if (!params.communityId) {
          return []
        }
        const res = await $request.get(`/api-parking/parking/advisor/community/${params.communityId}`)
        return (res || []).map((i) => ({ label: i.name, value: i.id }))
      } catch (error) {
        console.log(error)
        return []
      }
    },
    rules: [{ required: true, message: '原销售不能为空' }],
  },
  {
    label: '现销售',
    prop: 'toAdvisorId',
    type: 'select',
    linkage: 'communityId',
    options: async (params) => {
      try {
        if (!params.communityId) {
          return []
        }
        const res = await $request.get(`/api-parking/parking/advisor/community/${params.communityId}`)
        return (res || []).map((i) => ({ label: i.name, value: i.id }))
      } catch (error) {
        console.log(error)
        return []
      }
    },
    rules: [{ required: true, message: '现销售不能为空' }],
  },
]
const emits = defineEmits(['change'])

const dialogVisible = ref(false)

const colse = () => {
  dialogVisible.value = false
}

const ruleFormRef = shallowRef(null)
const tbcFormRef = shallowRef(null)
const formData = reactive({})
const handleChange = (value) => {
  Object.assign(formData, value.value)
}
const onSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          ...formData,
        }
        await $request.post('/api-parking/parking/advisor/transfer', { params })
        ElMessage({ type: 'success', message: '操作成功' })
        emits('change')
        colse()
      } catch (error) {
        return Promise.reject(error)
      }
    }
    return false
  })
}

const open = (info) => {
  const val = { ...info }
  Object.keys(formData).forEach((key) => {
    delete formData[key]
  })
  Object.assign(formData, val)
  dialogVisible.value = true
  nextTick(() => {
    tbcFormRef.value.set(formData)
    ruleFormRef.value.resetFields()
  })
}

watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      tbcFormRef.value.reset()
    }
  }
)

defineExpose({
  open,
})
</script>

<style lang="scss" scoped></style>
